package org.pisces.cas;

import java.security.GeneralSecurityException;
import java.util.HashMap;
import java.util.Map;

import org.apereo.cas.authentication.Credential;
import org.apereo.cas.authentication.HandlerResult;
import org.apereo.cas.authentication.PreventedException;
import org.apereo.cas.authentication.handler.support.AbstractPreAndPostProcessingAuthenticationHandler;
import org.apereo.cas.authentication.principal.PrincipalFactory;
import org.apereo.cas.services.ServicesManager;
import org.apereo.cas.web.support.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;

public class MyAuthenticationHandler extends AbstractPreAndPostProcessingAuthenticationHandler{

	
	@Autowired
	private JdbcTemplate jdbcTemplate;
	
	public MyAuthenticationHandler(String name, ServicesManager servicesManager, PrincipalFactory principalFactory,
			Integer order) {
		super(name, servicesManager, principalFactory, order);
	}

	@Override
	public boolean supports(Credential credential) {
		 return credential instanceof MyCredential;
	}

	@Override
	protected HandlerResult doAuthentication(Credential credential)
			throws GeneralSecurityException, PreventedException {
		Long result = jdbcTemplate.queryForObject("select count(1) from cas_user",Long.class);
		System.out.println(result);
		MyCredential myCredential = (MyCredential) credential;
		Map<String,Object> map = new HashMap<>();
		map.put("username", "系统管理员");
		map.put("id", 111);
        return createHandlerResult(myCredential, this.principalFactory.createPrincipal(myCredential.getUsername(), map), null);
	}


	
	/*
	private final JdbcTemplate jdbcTemplate;


	  protected JdbcTemplate getJdbcTemplate() {
	        return this.jdbcTemplate;
	    }

	public MyAuthenticationHandler(String name, ServicesManager servicesManager, PrincipalFactory principalFactory,
			Integer order, DataSource dataSource) {
		super(name, servicesManager, principalFactory, order, dataSource);
		this.jdbcTemplate = new JdbcTemplate(dataSource);
	}

	@Override
	protected HandlerResult authenticateUsernamePasswordInternal(UsernamePasswordCredential credential,
			String originalPassword) throws GeneralSecurityException, PreventedException {
		System.out.println(credential instanceof RememberMeUsernamePasswordCredential);
	//	MyCredential myCredential = (MyCredential) credential;
	//	System.out.println(myCredential.getCode());
		String username = "admin";
		Long result = jdbcTemplate.queryForObject("select count(1) from cas_user where username =?",Long.class,username);
		System.out.println("result======"+result);
		System.out.println("username:"+credential.getUsername());
		System.out.println("passport:"+credential.getPassword());
		Map<String,Object> map = new HashMap<>();
		map.put("username", "系统管理员");
		map.put("id", 111);
		 return createHandlerResult(credential,
                 this.principalFactory.createPrincipal(credential.getId(),map), null);
	}
*/


}
